<?php

namespace App\Models;
use App\Notifications\ResetPassword;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public static function boot()
    {
          parent::boot();
          static::creating(function ($user) {
            $user->activation_token=str_random(30);
          });

    }

    //头像 生成用了第三方的gravatar服务 邮箱hash
    public function gravatar($size = '100')
    {
       $hash = md5(strtolower(trim($this->attributes['email'])));
       return "http://www.gravatar.com/avatar/$hash?s=$size";
    }

    //发送邮件

    public function sendPasswordResetNotification($token)
    {
       $this->Notify(new ResetPassword($token));

    }
    //一个用户可以拥有很多微博
    public function statuses()
    {

      return $this->hasMany(Status::class);
    }

    public function feed()
    {
      //dd($this->statuses());
      return $this->statuses()
                  ->orderBy('created_at','desc');
    }

    //取出粉丝列表 [多对多]
    public function followers()
    {
      return $this->belongsToMany(User::class,'followers','user_id','follower_id');
    }

    //取出关注人列表
    public function followings()
    {

      return $this->belongsToMany(User::class,'followers','follower_id','user_id');
    }
   //关注
    public function follow($user_ids)
    {
          if(!is_array($user_ids)){
              $user_ids=compact('user_ids');
           }
           $this->followings()->sync($user_ids,false);

    }
    //取消关注
    public function unfollow($user_ids)
    {
        if(!is_array($user_ids)){
          $user_ids=compact('user_ids');
        }
        $this->followings()->detach($user_ids);
    }

    //is_followings

    public function isFollowing($user_id)
    {

         return $this->followings()->contains($user_id);
    }

}
